package Base

import (
	"strconv"
	. "westarry/gin-fox/gin-fox"
	ginfox "westarry/gin-fox/gin-fox"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type BaseModel struct {
	gorm.Model
}

type Model interface {
	TableName() string
}

func (_self *BaseModel) GetOne(model Model, id int) {
	ginfox.Gc.D.Table(model.TableName()).Find(&model)

}

// Pager /**
func (_self BaseModel) Pager(query *gorm.DB, c *gin.Context) map[string]any {
	parameters := _self.GetQueryParams(c)
	page, _ := strconv.Atoi(parameters["page"].(string))
	pageSize, _ := strconv.Atoi(parameters["size"].(string))
	var total int64
	var count int64
	if page == 0 {
		page = 1
	}
	if pageSize == 0 {
		pageSize = Gc.C.Pager.Size
	}
	offset := (page - 1) * pageSize
	data := make(map[string]interface{})
	list := make([]map[string]interface{}, 0)
	query.Count(&total).Limit(pageSize).Offset(offset).Find(&list).Count(&count)
	data["data"] = list
	data["total"] = count
	data["count"] = count
	data["page"] = page
	return data
}
func (_self BaseModel) GetQueryParams(c *gin.Context) map[string]any {
	query := c.Request.URL.Query()
	var queryMap = make(map[string]any, len(query))
	for k := range query {
		queryMap[k] = c.Query(k)
	}
	return queryMap
}
